<?php
namespace app\home\controller;

use Sunra\PhpSimple\HtmlDomParser;
use think\Controller;
use think\Db;
use think\Exception;
use Wxcrypt\Wxcrypt;
vendor('taobao.TopSdk');
class Mina extends Controller
{

    /**
     * 登录
     * @return array|string
     */
    public function login()
    {
        $code = input('code', '');
        try{
            if (empty($code)) {
                throw new Exception("code不能为空！");
            }
            $appid = config('AppID');
            $secret = config('AppSecret');
            $url="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
            $result = file_get_contents($url);
            $arr = json_decode($result,true);
            $is_new = 0; //是否是新用户 0否 1是
            if(isset($arr['openid']) && isset($arr['session_key'])){
                $info = Db::name('member')->where(['openid'=>$arr['openid']])->find();
                if(empty($info)){
                    $data['reg_ip'] = getIPaddress();
                    $data['reg_time'] = time();
                    $data['last_login_ip'] = getIPaddress();
                    $data['last_login_time'] = time();
                    $data['openid'] = $arr['openid'];
                    $data['level'] = 1;
                    $id = Db::name('member')->insertGetId($data);
                    Db::name('member')->where(['id'=>$id])->setField('pid_str','0_'.$id);
                    $is_new = 1;
                    $user_info = Db::name('member')->where(['id'=>$id])->find();
                }else{
                    $user_info = $info;
                }
                $sessionid = get_uuid();
                cache($sessionid, $arr['session_key'].'_'.$arr['openid']);
                $arrs['sessionid'] = $sessionid;
                $arrs['is_new'] = $is_new;
                $arrs['user_info'] = $user_info;
            }else{
                throw new Exception('信息获取失败');
            }
            return(json_encode(['code'=>200,'msg'=>"success",'data'=>$arrs]));
        }catch(Exception $e){
            return(['code'=>0,'msg'=>$e->getMessage()]);
        }
    }

    /**
     * 获取用户信息
     */
    public function get_userinfo()
    {
        $rawData = input('rawData', '');
        $signature = input('signature', '');
        $encryptedData = input('encryptedData', '');
        $sessionid = input('sessionid', '');
        $iv = input('iv', '');
        try{
            //对比签名
            $info = cache($sessionid);
            $sesson_key = substr($info,0,strrpos($info,'_'));
            $signature2 = sha1($rawData . $sesson_key);
            if ($signature2 !== $signature){
                throw new Exception("signNotMatch");
            }
            $pc = new Wxcrypt(config('AppID'),$sesson_key);
            $errCode = $pc->decryptData($encryptedData,$iv,$data);
            if ($errCode !== 0) {
                throw new Exception("encryptDataNotMatch");
            }
            $result = json_decode($data,true);
            Db::name('member')->where(['openid'=>$result['openId']])->update(['headimgurl'=>$result['avatarUrl'],'nickname'=>$result['nickName'],'sex'=>$result['gender'],'city'=>$result['city'],'province'=>$result['province'],'country'=>$result['country'],'unionId'=>$result['unionId']]);
            $user_info = Db::name('member')->where(['openid'=>$result['openId']])->find();
            return(json_encode(['code'=>200,'msg'=>"success",'data'=>$user_info]));
        }catch(Exception $e){
            return(['code'=>0,'msg'=>$e->getMessage()]);
        }
    }

    /**
     * 商品列表
     */
    public function itemlist(){
        $nav = input('param.nav',3); //默认全部商品（1实时跑单商品，2爆单榜商品，3全部商品，4纯视频单，5聚淘专区）
        $coupon_min = input('param.coupon_min',0); //优惠券最低金额
        $cid = input('param.cid',0); //商品类目：0全部，1女装，2男装，3内衣，4美妆，5配饰，6鞋品，7箱包，8儿童，9母婴，10居家，11美食，12数码，13家电，14其他，15车品，16文体
        $back = input('param.back',10); //每页返回条数（请在1,2,10,20,50,100,120,200,500,1000中选择一个数值返回）
        $min_id = input('param.min_id',1);//分页，用于实现类似分页抓取效果，来源于上次获取后的数据的min_id值，默认开始请求值为1
        $sort = input('param.sort',0);//0.综合（最新），1.券后价(低到高)，2.券后价（高到低），3.券面额（高到低），4.月销量（高到低），5.佣金比例（高到低），6.券面额（低到高），7.月销量（低到高），8.佣金比例（低到高），9.全天销量（高到低），10全天销量（低到高），11.近2小时销量（高到低），12.近2小时销量（低到高）
        $url= 'http://v2.api.haodanku.com/itemlist/apikey/'.config('hdkkey').'/nav/'.$nav.'/cid/'.$cid.'/back/'.$back.'/min_id/'.$min_id.'/sort/'.$sort.'/coupon_min/'.$coupon_min;
        try{
            $data = file_get_contents($url);
            $data = json_decode($data,true);
            if (!empty($data['data'])){
                foreach ($data['data'] as $k=>$v){
                    if ($v['itemsale'] >9999){
                        $data['data'][$k]['itemsale'] = round($v['itemsale'] / 10000,1).'万';
                    }
                    $data['data'][$k]['itempic'] = $v['itempic'].'_310x310.jpg';
                }
            }
            return(json_encode($data));
        }catch (Exception $e){
            return(['code'=>0,'msg'=>$e->getMessage()]);
        }
    }

    /**
     * 今日上新等接口
     */
    public function items_cate(){
        $type = input('param.type',1); //商品筛选类型：type=1是今日上新（当天新券商品），type=2是9.9包邮，type=3是30元封顶，type=4是聚划算，type=5是淘抢购，type=6是0点过夜单，type=7是预告单，type=8是品牌单，type=9是天猫商品，type=10是视频单
        $sort = input('param.sort',0); //排序 0.综合（最新），1.券后价(低到高)，2.券后价（高到低），3.券面额，4.销量,5.佣金比例
        $min_id = input('param.min_id',1);//分页，用于实现类似分页抓取效果，来源于上次获取后的数据的min_id值，默认开始请求值为1
        $url= 'http://v2.api.haodanku.com/column/apikey/'.config('hdkkey').'/type/'.$type.'/back/10/min_id/'.$min_id.'/sort/'.$sort;
        try{
            $data = file_get_contents($url);
            $data = json_decode($data,true);
            if (!empty($data['data'])){
                foreach ($data['data'] as $k=>$v){
                    if ($v['itemsale'] >9999){
                        $data['data'][$k]['itemsale'] = round($v['itemsale'] / 10000,1).'万';
                    }
                    $data['data'][$k]['itempic'] = $v['itempic'].'_310x310.jpg';
                }
            }
            return(json_encode($data));
        }catch (Exception $e){
            return(['code'=>0,'msg'=>$e->getMessage()]);
        }
    }

    /**
     * 轮播
     */
    public function banner(){
        $url = 'http://v2.api.haodanku.com/get_subject/apikey/'.config('hdkkey');
        $data = file_get_contents($url);
        if (!empty($data)){
            $data_arr = json_decode($data,true);
            foreach ($data_arr['data'] as $k=>$v){
                $data_arr['data'][$k]['type'] = 'subject';
                $data_arr['data'][$k]['shoptype'] = '';
            }
        }
        $data = json($data_arr);
        return($data);
    }


    /**
     * 精美专题
     */
    public function subject(){
        $url = 'http://v2.api.haodanku.com/get_subject/apikey/'.config('hdkkey');
        $data = file_get_contents($url);
        return($data);
    }

    /**
     * 精美专题商品
     */
    public function subject_item(){
        $id = input('param.id','');
        if (empty($id) || $id==0){
            return(json_encode(['code'=>0,'msg'=>'fali']));
        }
        $url = 'http://v2.api.haodanku.com/get_subject_item/apikey/'.config('hdkkey').'/id/'.$id;
        $data = file_get_contents($url);
        $data = json_decode($data,true);
        if (!empty($data['data'])){
            foreach ($data['data'] as $k=>$v){
                if ($v['itemsale'] >9999){
                    $data['data'][$k]['itemsale'] = round($v['itemsale'] / 10000,1).'万';
                }
                $data['data'][$k]['itempic'] = $v['itempic'].'_310x310.jpg';
            }
        }
        return(json_encode($data));
    }

    /**
     * 高佣API
     */
    public function ratesurl(){
        $url = 'http://v2.api.haodanku.com/ratesurl/apikey/'.config('hdkkey');
        $data['itemid'] = input('param.itemid','');
        if(empty($data['itemid'])){
            return(json_encode(['code'=>0,'msg'=>'请输入商品id']));
        }
        $data['apikey'] = config('hdkkey');
        $data['pid'] = config('pid');
        $result = send_post($url,$data);
        return $result;
    }

    /**
     * 关键词搜索商品页
     */
    public function keyword_items(){
        $keyword = input('param.keyword','');
        $min_id = input('param.min_id',1);
        $sort = input('param.sort',0);
        if(empty($keyword)){
            return (json_encode(['code'=>0,'msg'=>'请输入关键词']));
        }
        $url = 'http://v2.api.haodanku.com/get_keyword_items/apikey/'.config('hdkkey').'/keyword/'.urldecode(urldecode($keyword)).'/back/10/sort/'.$sort.'/cid/0/min_id/'.$min_id;
        $data = file_get_contents($url);
        return $data;
    }

    /**
     * 淘宝全站搜索
     */
    public function supersearch(){
        $keyword = input('param.keyword','');
        $min_id = input('param.min_id',1);
        $sort = input('param.sort',0);
        if(empty($keyword)){
            return (json_encode(['code'=>0,'msg'=>'请输入关键词']));
        }
        $keyword = urlencode(urlencode($keyword));
        if($sort == 0){
            $url = 'http://v2.api.haodanku.com/supersearch/apikey/'.config('hdkkey').'/keyword/'.$keyword.'/back/10/min_id/'.$min_id.'/tb_p/'.$min_id.'/sort/0/is_tmall/0/is_coupon/0';
        }elseif($sort == 1){
            $url = 'http://v2.api.haodanku.com/supersearch/apikey/'.config('hdkkey').'/keyword/'.$keyword.'/back/10/min_id/'.$min_id.'/tb_p/'.$min_id.'/sort/2/is_tmall/0/is_coupon/0';
        }elseif($sort == 2){
            $url = 'http://v2.api.haodanku.com/supersearch/apikey/'.config('hdkkey').'/keyword/'.$keyword.'/back/10/min_id/'.$min_id.'/tb_p/'.$min_id.'/sort/0/is_tmall/0/is_coupon/1';
        }else{
            $url = 'http://v2.api.haodanku.com/supersearch/apikey/'.config('hdkkey').'/keyword/'.$keyword.'/back/10/min_id/'.$min_id.'/tb_p/'.$min_id.'/sort/0/is_tmall/1/is_coupon/0';
        }
        $data = file_get_contents($url);
        return $data;
    }

    /**
     * 关热搜关键词记录
     */
    public function hot_key(){
        $url = 'http://v2.api.haodanku.com/hot_key/apikey/'.config('hdkkey');
        $data = file_get_contents($url);
        return $data;
    }


    /**
     * 单品详情
     */
    public function item_detail2(){
        $itemid = input('param.itemid','');
        if(empty($itemid)){
            return (json_encode(['code'=>0,'msg'=>'请传入商品id']));
        }
        $url = 'https://v2.api.haodanku.com/item_detail/apikey/'.config('hdkkey').'/itemid/'.$itemid;
        $data = file_get_contents($url);
        $content_ori=strip_tags($data);
        $content_arr=json_decode($content_ori,true);
        if(!empty($content_arr['data'])){
            $content_arr['data']['itempic_list'][] = $content_arr['data']['itempic'];
        }
        return json($content_arr);
    }

    /**
     * 猜你喜欢
     */
    public function similar_info(){
        $itemid = input('param.itemid','');
        if(empty($itemid)){
            return (json_encode(['code'=>0,'msg'=>'请传入商品id']));
        }
        $url = 'http://v2.api.haodanku.com/get_similar_info/apikey/'.config('hdkkey').'/itemid/'.$itemid;
        $data = file_get_contents($url);
        return $data;
    }

    /**
     * 淘口令
     */
    public function linkTkl(){
        $data['link'] = input('param.link','');
        $data['type'] = input('param.type','B');
        if(empty($data['link'])){
            return (json_encode(['code'=>0,'msg'=>'请传入商品链接']));
        }
        $url = 'http://api.chaozhi.hk/tb/linkTkl';
        $result = httpRequest($url,'POST',$data);
        return $result;
    }
    /**
     * 淘口令
     */
    public function tkl(){
        $title = input('param.title','');
        $logo = input('param.logo','');
        $url = input('param.link','');
        $c = new \TopClient();
        $c->appkey = '24741714';
        $c->secretKey = 'f2f5a9c7417b0ab85fbda53989b3b5ec';
        $req = new \TbkTpwdCreateRequest();
        $req->setUserId("810608219");
        $req->setText($title);
        $req->setUrl($url);
        $req->setLogo($logo);
        $req->setExt("{}");
        $resp = $c->execute($req);
        $data = object_array($resp);
        if (isset($data['data']['model']) && !empty($data['data']['model'])){
            return json(['code'=>1,'data'=>$data['data']['model']]);
        }else{
            return json(['code'=>0,'data'=>'']);
        }

    }

    /**
     * 下单流程图
     */
    public function flow_image(){
        return json(['code'=>1,'msg'=>'success','data'=>'http://image.anymean.com/flow.png']);
    }



    /**
     * 设置隐藏 线上20180625
     */
    public function check(){
        return json(['code'=>1,'data'=>1]);
    }

    /**
     * 设置隐藏
     */
    public function check_v1(){
        return json(['code'=>1,'data'=>1]);
    }

    /**
     * 单品详情
     */
    public function item_detail(){
        $itemid = input('param.itemid','');
        if(empty($itemid)){
            return (json_encode(['code'=>0,'msg'=>'请传入商品id']));
        }
        $content_arr = cache(md5('detail'.$itemid));
        if (empty($content_arr)){
            $url = 'https://v2.api.haodanku.com/item_detail/apikey/'.config('hdkkey').'/itemid/'.$itemid;
            $data = file_get_contents($url);
            $content_ori=strip_tags($data);
            $content_arr=json_decode($content_ori,true);
            /*if ($content_arr['data']['shoptype'] == 'B'){
                $item_url = 'https://detail.tmall.com/item.htm?id='.$content_arr['data']['itemid'];
                $dom = HtmlDomParser::file_get_html($item_url);
                $img = $dom->find('#J_UlThumb', 0)->find('img');
                foreach ($img as $element){
                    $pict = mb_convert_encoding($element->src, "UTF-8", "GBK");//商品图片
                    if (empty($pict)){
                        $picture = 'http:'.mb_convert_encoding($element->getAttribute('data-src'), "UTF-8", "GBK");//商品图片
                        $pic[] = str_replace('_50x50','_400x400',$picture);
                    }else{
                        $picture = 'http:'.$pict;
                        $pic[] = str_replace('_60x60q90','_430x430q90',$picture);
                    }
                }
            }else{
                $item_url = 'https://item.taobao.com/item.htm?&id='.$content_arr['data']['itemid'];
                $dom = HtmlDomParser::file_get_html($item_url);
                $img = $dom->find('#J_UlThumb',0)->find('img');
                foreach ($img as $element){
                    $picture = 'http:' . mb_convert_encoding($element->getAttribute('data-src'), "UTF-8", "GBK");//商品图片
                    $pic[] = str_replace('_50x50','_400x400',$picture);
                }
            }*/
            $pic = self::small_images($itemid);
            if(!empty($pic)){
                $content_arr['data']['itempic_list'] = $pic;
            }else{
                $content_arr['data']['itempic_list'][] = $content_arr['data']['itempic'];
            }
            $pic_list = file_get_contents('http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7Bitem_num_id%3A'.$itemid.'%7D&type=jsonp&dataType=jsonp');
            $start1=strstr($pic_list,"callback(");
            $str = substr($start1,9);
            $newstr = substr($str,0,strlen($str)-1);
            $list = json_decode($newstr,true);
            $content_arr['data']['pic_list'] = $list['data']['images'];
            cache(md5('detail'.$itemid),$content_arr,3600*24);//缓存24个小时
        }
        return json($content_arr);
    }

    /**
     * 图文详情列表
     */
    public function pictures($itemid,$shoptype='B'){
        if ($shoptype == 'B'){
            $dom = HtmlDomParser::file_get_html('https://detail.tmall.com/item.htm?id='.$itemid);
            $start1=strstr($dom,"{\"api\"");
            $tp = strpos($start1,"</script>");
            $str = substr($start1,0,$tp);
            $str=iconv("GBK", "UTF-8", $str);
            $new_str = substr($str, 0, -11);
            $arr = json_decode($new_str,true);
            $doms = HtmlDomParser::file_get_html('http:'.$arr['api']['descUrl']);
            $img = $doms->find('img');
            foreach ($img as $element){
                $picture = mb_convert_encoding($element->src, "UTF-8", "GBK");//商品图片
                $info1=pathinfo($picture);
                if ($info1['extension'] == 'jpg'){
                    $pic[] = $picture;
                }
            }
            return $pic;
        }else{
            $dom = HtmlDomParser::file_get_html('https://item.taobao.com/item.htm?id='.$itemid);
            $start1=strstr($dom,"location.protocol==='http:' ? '");
            $tp = strpos($start1,"' :");
            $str = 'http:'.substr($start1,31,$tp-31);
            $doms = HtmlDomParser::file_get_html($str);
            $img = $doms->find('p',-1)->find('img');
            foreach ($img as $element){
                $picture = mb_convert_encoding($element->src, "UTF-8", "GBK");//商品图片
                $pic[] = $picture;
            }
            return $pic;
        }
    }

    public function small_images($itemid){
        $url = 'http://demo2.b2ef.cn/index.php?g=wap&m=detail&r=small_images&goods_id='.$itemid;//淘客基地
        $small_images = file_get_contents($url);
        $list = json_decode($small_images,true);
        foreach ($list['data'] as $k=>$v){
            $pic[] = $v['img'];
        }
        return $pic;
    }
    public function get_pic(){
        $pic_list = file_get_contents('http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7Bitem_num_id%3A564491445765%7D&type=jsonp&dataType=jsonp');
        $start1=strstr($pic_list,"callback(");
        $str = substr($start1,9);
        $newstr = substr($str,0,strlen($str)-1);
        $list = json_decode($newstr,true);
        foreach($list['data']['images'] as $k=>$v){
            echo '<p><img src="'.$v.'"></p>';
        }
    }

    /**
     * 获取商品信息
     */
    public function detail_v1()
    {

        $itemid = input('param.itemid', '');
        $shoptype = input('param.shoptype', 'C');
        try {
            if (empty($itemid)) {
                throw new Exception('请传入商品id');
            }
            $content_arr = cache(md5('detail' . $itemid));
            if (empty($content_arr)) {
                $url = 'https://v2.api.haodanku.com/item_detail/apikey/' . config('hdkkey') . '/itemid/' . $itemid;//单品详情
                $data = file_get_contents($url);
                $content_ori = strip_tags($data);
                $content_arr = json_decode($content_ori, true);//商品信息
                $data_info = [];
                if ($content_arr['code'] == 0) {
                    $item_info = self::item_info($itemid, $shoptype);
                    if ($item_info['code'] == 200) {
                        $data_info = $item_info['data'];
                    } else {
                        throw new Exception($item_info['msg']);
                    }
                } else {
                    $data_info['itemid'] = $itemid;
                    $data_info['itemtitle'] = $content_arr['data']['itemtitle'];
                    $data_info['itemdesc'] = $content_arr['data']['itemdesc'];
                    $data_info['itemprice'] = $content_arr['data']['itemprice'];
                    $data_info['itemsale'] = $content_arr['data']['itemsale'];
                    $data_info['itempic'] = $content_arr['data']['itempic'];
                    $data_info['itemendprice'] = $content_arr['data']['itemendprice'];
                    $data_info['couponmoney'] = $content_arr['data']['couponmoney'];
                    $data_info['shoptype'] = $shoptype;
                    $data_info['couponstarttime'] = date("Y.m.d", $content_arr['data']['couponstarttime']);
                    $data_info['couponendtime'] = date("Y.m.d", $content_arr['data']['couponendtime']);
                }
                //猜你喜欢
                $similar_info = file_get_contents('http://v2.api.haodanku.com/get_similar_info/apikey/' . config('hdkkey') . '/itemid/' . $itemid);
                $similar_info = strip_tags($similar_info);
                $similar_arr = json_decode($similar_info, true);
                if ($similar_arr['code'] == 1) {
                    $data_info['similar_list'] = $similar_arr['data'];
                } else {
                    $data_info['similar_list'] = [];
                }
                //商品信息
                //$info = file_get_contents('http://zjw.anymean.com/public/index.php/index/index/info?itemid=' . $itemid);
                if (!empty($info)) {
                    $infos = json_decode($info, true);
                }
                if (!empty($infos['item'])) {
                    $data_info['itempic_list'] = $infos['item']['images']; //轮播图
 //                   $data_info['itempic_list'][] = $infos['item']['images'][0]; //轮播图 审核
                    $data_info['seller'] = $infos['seller']; //店铺信息
                    foreach ($infos['groupProps'][0]['基本信息'] as $k=>$v){
                        foreach ($v as $key=>$val){
                            $infos['groupPropst'][$k]['key'] = $key;
                            $infos['groupPropst'][$k]['val'] = $val;
                        }
                    }
                    $data_info['groupPropst'] = $infos['groupPropst'];
                    $data_info['rate'] = $infos['rate']; //评论
                } else {
                    $pic = self::small_images($itemid); //轮播图
                    if (!empty($pic)) {
                        $data_info['itempic_list'] = $pic;//轮播图
                    } else {
                        $data_info['itempic_list'][] = $content_arr['data']['itempic'];//轮播图
                    }
                }
                //获取图文详情
                $pic_list = file_get_contents('http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7Bitem_num_id%3A' . $itemid . '%7D&type=jsonp&dataType=jsonp');
                $start1 = strstr($pic_list, "callback(");
                $str = substr($start1, 9);
                $newstr = substr($str, 0, strlen($str) - 1);
                $list = json_decode($newstr, true);
                $data_info['pic_list'] = $list['data']['images'];
            cache(md5('detail'.$itemid),$data_info,7200*5);//缓存24个小时
            }else{
                $data_info = $content_arr;
            }
            return json(['code' => 1, 'data' => $data_info]);
        } catch (Exception $e) {
            return json(['code' => 0, 'data' => [], 'msg' => $e->getMessage()]);
        }
    }


    /**
     * 获取商品信息 线上20180625
     */
    public function detail_v2(){

        $itemid = input('param.itemid','');
        if(empty($itemid)){
            return (json_encode(['code'=>0,'msg'=>'请传入商品id']));
        }
        $content_arr = cache(md5('detail'.$itemid));
        if (empty($content_arr)){
            $url = 'https://v2.api.haodanku.com/item_detail/apikey/'.config('hdkkey').'/itemid/'.$itemid;
            $data = file_get_contents($url);
            $content_ori=strip_tags($data);
            $content_arr=json_decode($content_ori,true);//所有的商品信息
            $content_arr['data']['couponstarttime'] = date("Y.m.d",$content_arr['data']['couponstarttime']);
            $content_arr['data']['couponendtime'] = date("Y.m.d",$content_arr['data']['couponendtime']);
            //猜你喜欢
            $similar_info = file_get_contents('http://v2.api.haodanku.com/get_similar_info/apikey/'.config('hdkkey').'/itemid/'.$itemid);
            $similar_info=strip_tags($similar_info);
            $similar_arr=json_decode($similar_info,true);
            if($similar_arr['code'] == 1){
                $content_arr['data']['similar_list'] =  $similar_arr['data'];
            }else{
                $content_arr['data']['similar_list'] = [];
            }
            //商品信息
            $info = file_get_contents('http://zjw.anymean.com/public/index.php/index/index/info?itemid='.$itemid);
            if(!empty($info)){
                $infos = json_decode($info,true);
            }
            //商品的信息
            if(!empty($infos['item']['images'])){
//                $content_arr['data']['itempic_list'] = $infos['item']['images']; //轮播图
                $content_arr['data']['itempic_list'][] = $infos['item']['images'][0]; //轮播图 审核
                $content_arr['data']['seller'] = $infos['seller']; //店铺信息
                foreach ($infos['groupProps'][0]['基本信息'] as $k=>$v){
                    foreach ($v as $key=>$val){
                        $infos['groupPropst'][$k]['key'] = $key;
                        $infos['groupPropst'][$k]['val'] = $val;
                    }
                }
                $content_arr['data']['groupPropst'] = $infos['groupPropst'];
                $content_arr['data']['rate'] = $infos['rate']; //评论
            }else{
                $pic = self::small_images($itemid); //轮播图
                if(!empty($pic)){
                    $content_arr['data']['itempic_list'] = $pic;//轮播图
                }else{
                    $content_arr['data']['itempic_list'][] = $content_arr['data']['itempic'];//轮播图
                }
            }
//            $content_arr['data']['itempic_list'][] = $content_arr['data']['itempic'];  //审核用
            //获取图文详情
            $pic_list = file_get_contents('http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7Bitem_num_id%3A'.$itemid.'%7D&type=jsonp&dataType=jsonp');
            $start1=strstr($pic_list,"callback(");
            $str = substr($start1,9);
            $newstr = substr($str,0,strlen($str)-1);
            $list = json_decode($newstr,true);
            $content_arr['data']['pic_list'] = $list['data']['images'];
            cache(md5('detail'.$itemid),$content_arr,3600*5);//缓存24个小时
        }
        return json($content_arr);
    }


    /**
     * 获取评论列表
     */
    public function comment_list(){
        $itemid = input('param.itemid','');
        $sellerid = input('param.sellerid','');
        $page = input('param.page',1);
        $comment_list = file_get_contents('http://zjw.anymean.com/public/index.php/index/index/comment?itemid='.$itemid.'&sellerid='.$sellerid.'&page='.$page);
        if(!empty($comment_list)){
            $comments= json_decode($comment_list,true);
            $data['total'] = $comments['total'];
            $data['per_page'] = 10;
            $data['current_page'] = $comments['page'];
            $data['lastPage'] = $comments['lastPage'];
            $data['data'] = $comments['rateList'];
        }else{
            $data['total'] = 0;
            $data['per_page'] = 10;
            $data['current_page'] = 1;
            $data['lastPage'] = 1;
            $data['data'] = [];
        }
        return json(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    /**
     * 获取指定商品信息
     * @param $itemid 商品id
     * @param $shoptype 商品类型 B天猫 C淘宝
     * @return array 商品信息
     */
    public function item_info($itemid,$shoptype){

        if ($shoptype == 'B'){
            $goods_url = 'https://detail.tmall.com/item.htm?id='.$itemid;
        }else{
            $goods_url = 'https://item.taobao.com/item.htm?id='.$itemid;
        }
        try{
            $url = 'http://pub.alimama.com/items/search.json?q='.urlencode($goods_url);
            $data = file_get_contents($url);
            $arr = json_decode($data,true);
            if ($arr['ok'] !=true){
                throw new Exception('信息获取失败');
            }
            if (empty($arr['data']['pageList'])){
                throw new Exception('暂无该商品信息');
            }
            $info['itemid'] = $itemid;
            $info['itemtitle'] = $arr['data']['pageList'][0]['title'];
            $info['itemdesc'] = '';
            $info['itemprice'] = $arr['data']['pageList'][0]['zkPrice'];
            $info['itemsale'] = $arr['data']['pageList'][0]['biz30day'];
            $info['itempic'] = 'http:'.$arr['data']['pageList'][0]['pictUrl'];
            if ($arr['data']['pageList'][0]['couponInfo'] == '无'){
                $info['itemendprice'] = $arr['data']['pageList'][0]['zkPrice'];
                $info['couponstarttime'] = '';
                $info['couponendtime'] = '';
                $info['couponmoney'] = 0;
            }else{
                $info['itemendprice'] = $arr['data']['pageList'][0]['zkPrice'] - $info['itemendprice'] = $arr['data']['pageList'][0]['couponAmount'];
                $info['couponstarttime'] = $arr['data']['pageList'][0]['couponEffectiveStartTime'];
                $info['couponendtime'] = $arr['data']['pageList'][0]['couponEffectiveEndTime'];
                $info['couponmoney'] = $arr['data']['pageList'][0]['couponAmount'];
            }
            $info['shoptype'] = $shoptype;
            return ['code'=>200,'data'=>$info,'msg'=>'success'];

        }catch (Exception $e){
            return ['code'=>0,'data'=>[],'msg'=>$e->getMessage()];
        }
    }

     /**
     * 代理商申请
     */
    public function agency_application(){
        $name = input('name',''); //真实姓名
        $uid = input('uid','');//用户uid
        $phone = input('phone','');//手机号
        $wx_account = input('wx_account','');//微信号
        $beizhu = input('beizhu','');//备注
        try{
Db::name('agents')->insert(['uid'=>$uid,'phone'=>$phone,'name'=>$name,'wxpay'=>$wx_account,'add_time'=>time()]);
            return json(['code'=>200,'msg'=>'success']);
        }catch(Exception $e){
            return json(['code'=>0,'data'=>[],'msg'=>$e->getMessage()]);
        }
    }

    /**
     * 把jsonp转为php数组
     * @param string $jsonp jsonp字符串
     * @param boolean $assoc 当该参数为true时，将返回array而非object
     * @return array
     */
    function jsonp_decode($jsonp, $assoc = false)
    {
        $jsonp = trim($jsonp);
        if(isset($jsonp[0]) && $jsonp[0] !== '[' && $jsonp[0] !== '{') {
            $begin = strpos($jsonp, '(');
            if(false !== $begin)
            {
                $end = strrpos($jsonp, ')');
                if(false !== $end)
                {
                    $jsonp = substr($jsonp, $begin + 1, $end - $begin - 1);
                }
            }
        }
        return json_decode($jsonp, $assoc);
    }

}